"""
持仓分析页面
提供投资组合分析、风险评估、绩效归因等功能
"""

import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional

from ..components.common import (
    create_sidebar_navigation, make_api_request, 
    display_loading_spinner, show_success_message, show_error_message
)
from ..components.metrics import create_metric_card, create_status_indicator
from ..components.charts import create_line_chart, create_bar_chart, create_pie_chart
from ..components.tables import create_data_table, create_editable_table
from ..components.filters import create_date_filter, create_multiselect_filter


def render_portfolio_analysis_page():
    """渲染持仓分析页面"""
    st.title("📈 持仓分析")
    
    # 侧边栏导航
    create_sidebar_navigation()
    
    # 创建标签页
    tab1, tab2, tab3, tab4, tab5 = st.tabs([
        "组合概览", "持仓分析", "风险分析", "绩效归因", "优化建议"
    ])
    
    with tab1:
        render_portfolio_overview_tab()
    
    with tab2:
        render_position_analysis_tab()
    
    with tab3:
        render_risk_analysis_tab()
    
    with tab4:
        render_performance_attribution_tab()
    
    with tab5:
        render_optimization_tab()


def render_portfolio_overview_tab():
    """渲染组合概览标签页"""
    st.header("投资组合概览")
    
    # 组合关键指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card("总资产", "645.8万", "💰", delta="25.8万", delta_color="normal")
    
    with col2:
        create_metric_card("持仓市值", "485.2万", "📊", delta="15.6万", delta_color="normal")
    
    with col3:
        create_metric_card("现金余额", "160.6万", "💳", delta="10.2万", delta_color="normal")
    
    with col4:
        create_metric_card("总收益率", "+18.5%", "📈", delta="3.2%", delta_color="normal")
    
    st.divider()
    
    # 资产配置
    st.subheader("资产配置")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 资产类别分布
        asset_allocation = pd.DataFrame({
            '资产类别': ['股票', '现金', '债券', '基金'],
            '市值': [485.2, 160.6, 0, 0],
            '占比': [75.1, 24.9, 0, 0]
        })
        
        create_pie_chart(
            asset_allocation,
            values_col='市值',
            names_col='资产类别',
            title="资产配置分布",
            height=300
        )
    
    with col2:
        # 行业分布
        industry_allocation = pd.DataFrame({
            '行业': ['银行', '电子', '食品饮料', '医药', '房地产', '其他'],
            '市值': [149.4, 97.0, 67.4, 48.5, 36.6, 86.3],
            '占比': [30.8, 20.0, 13.9, 10.0, 7.5, 17.8]
        })
        
        create_pie_chart(
            industry_allocation,
            values_col='市值',
            names_col='行业',
            title="行业配置分布",
            height=300
        )
    
    # 净值走势
    st.subheader("组合净值走势")
    
    # 模拟净值数据
    dates = pd.date_range(start='2023-01-01', end='2024-01-15', freq='D')
    nav_data = pd.DataFrame({
        '日期': dates,
        '组合净值': [1.0 + i * 0.0005 + np.random.normal(0, 0.008) for i in range(len(dates))],
        '基准净值': [1.0 + i * 0.0003 + np.random.normal(0, 0.006) for i in range(len(dates))],
        '超额收益': [(1.0 + i * 0.0005) - (1.0 + i * 0.0003) for i in range(len(dates))]
    })
    
    create_line_chart(
        nav_data,
        x_col='日期',
        y_col='组合净值',
        title="组合净值走势对比",
        height=400
    )
    
    # 关键统计指标
    st.subheader("关键统计指标")
    
    col1, col2 = st.columns(2)
    
    with col1:
        performance_stats = pd.DataFrame({
            '指标': ['年化收益率', '累计收益率', '月度胜率', '最大单日收益', '最大单日亏损'],
            '组合': ['18.5%', '+25.8%', '68.2%', '+3.8%', '-2.1%'],
            '基准': ['12.3%', '+15.2%', '58.7%', '+2.9%', '-3.2%'],
            '超额': ['+6.2%', '+10.6%', '+9.5%', '+0.9%', '+1.1%']
        })
        
        create_data_table(performance_stats, "收益统计")
    
    with col2:
        risk_stats = pd.DataFrame({
            '指标': ['波动率', '最大回撤', '夏普比率', 'VaR(95%)', '信息比率'],
            '组合': ['16.8%', '-8.5%', '1.92', '-2.3%', '1.45'],
            '基准': ['18.2%', '-12.1%', '1.35', '-2.8%', '-'],
            '相对': ['-1.4%', '+3.6%', '+0.57', '+0.5%', '1.45']
        })
        
        create_data_table(risk_stats, "风险统计")


def render_position_analysis_tab():
    """渲染持仓分析标签页"""
    st.header("持仓分析")
    
    # 持仓概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card("持仓股票", "18只", "📊", delta="2", delta_color="normal")
    
    with col2:
        create_metric_card("集中度", "30.8%", "🎯", delta="2.1%", delta_color="normal")
    
    with col3:
        create_metric_card("换手率", "15.2%", "🔄", delta="3.5%", delta_color="normal")
    
    with col4:
        create_metric_card("贝塔系数", "0.95", "📉", delta="0.05", delta_color="normal")
    
    st.divider()
    
    # 持仓明细
    st.subheader("持仓明细")
    
    # 模拟持仓数据
    positions = pd.DataFrame({
        '股票代码': ['000001.SZ', '000002.SZ', '600000.SH', '600036.SH', '000858.SZ', 
                   '002415.SZ', '000063.SZ', '600519.SH', '000568.SZ', '002304.SZ'],
        '股票名称': ['平安银行', '万科A', '浦发银行', '招商银行', '五粮液',
                   '海康威视', '中兴通讯', '贵州茅台', '泸州老窖', '洋河股份'],
        '行业': ['银行', '房地产', '银行', '银行', '食品饮料',
               '电子', '通信', '食品饮料', '食品饮料', '食品饮料'],
        '持仓数量': [8000, 2000, 6000, 1000, 300, 2500, 3000, 100, 800, 1200],
        '成本价': [12.20, 18.50, 8.80, 44.50, 165.00, 35.20, 28.50, 1850.00, 95.20, 85.30],
        '最新价': [12.50, 18.30, 8.90, 45.20, 168.50, 36.10, 29.80, 1920.00, 98.50, 88.20],
        '市值': [100000, 36600, 53400, 45200, 50550, 90250, 89400, 192000, 78800, 105840],
        '权重': ['20.6%', '7.5%', '11.0%', '9.3%', '10.4%', '18.6%', '18.4%', '39.6%', '16.2%', '21.8%'],
        '盈亏': [2400, -400, 600, 700, 1050, 2250, 3900, 7000, 2640, 3480],
        '盈亏率': ['2.46%', '-1.08%', '1.14%', '1.57%', '2.12%', '2.56%', '4.56%', '3.78%', '3.45%', '4.09%']
    })
    
    # 持仓筛选
    col1, col2, col3 = st.columns(3)
    
    with col1:
        industry_filter = create_multiselect_filter(
            positions, '行业', '行业筛选', key='position_industry'
        )
    
    with col2:
        weight_range = st.slider("权重范围(%)", 0, 50, (0, 50))
    
    with col3:
        sort_by = st.selectbox("排序方式", ["权重", "盈亏", "盈亏率", "市值"])
    
    # 应用筛选
    filtered_positions = positions.copy()
    if industry_filter:
        filtered_positions = filtered_positions[filtered_positions['行业'].isin(industry_filter)]
    
    # 排序
    if sort_by == "权重":
        filtered_positions = filtered_positions.sort_values('市值', ascending=False)
    elif sort_by == "盈亏":
        filtered_positions = filtered_positions.sort_values('盈亏', ascending=False)
    elif sort_by == "盈亏率":
        filtered_positions = filtered_positions.sort_values('盈亏率', ascending=False)
    else:
        filtered_positions = filtered_positions.sort_values('市值', ascending=False)
    
    create_data_table(filtered_positions, "持仓详情")
    
    # 持仓分析图表
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("权重分布")
        
        top_positions = positions.nlargest(8, '市值')
        create_bar_chart(
            top_positions,
            x_col='股票名称',
            y_col='市值',
            title="前8大持仓",
            height=300
        )
    
    with col2:
        st.subheader("行业权重")
        
        industry_weight = positions.groupby('行业')['市值'].sum().reset_index()
        industry_weight['权重'] = industry_weight['市值'] / industry_weight['市值'].sum() * 100
        
        create_bar_chart(
            industry_weight,
            x_col='行业',
            y_col='权重',
            title="行业权重分布",
            height=300
        )
    
    # 持仓变化分析
    st.subheader("持仓变化分析")
    
    # 模拟持仓变化数据
    position_changes = pd.DataFrame({
        '日期': pd.date_range(start='2024-01-10', end='2024-01-15', freq='D'),
        '股票数量': [15, 16, 17, 18, 18, 18],
        '换手率': [8.5, 12.3, 15.2, 18.7, 15.2, 12.8],
        '集中度': [28.5, 29.2, 30.1, 30.8, 30.8, 30.5]
    })
    
    col1, col2 = st.columns(2)
    
    with col1:
        create_line_chart(
            position_changes,
            x_col='日期',
            y_col='换手率',
            title="换手率变化",
            height=250
        )
    
    with col2:
        create_line_chart(
            position_changes,
            x_col='日期',
            y_col='集中度',
            title="持仓集中度变化",
            height=250
        )


def render_risk_analysis_tab():
    """渲染风险分析标签页"""
    st.header("风险分析")
    
    # 风险指标概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card("组合波动率", "16.8%", "📊", delta="-1.4%", delta_color="inverse")
    
    with col2:
        create_metric_card("最大回撤", "-8.5%", "📉", delta="+3.6%", delta_color="normal")
    
    with col3:
        create_metric_card("VaR(95%)", "-2.3%", "⚠️", delta="+0.5%", delta_color="normal")
    
    with col4:
        create_metric_card("贝塔系数", "0.95", "📈", delta="-0.05", delta_color="inverse")
    
    st.divider()
    
    # 风险分解
    st.subheader("风险分解分析")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 风险贡献
        risk_contribution = pd.DataFrame({
            '股票': ['贵州茅台', '海康威视', '中兴通讯', '平安银行', '洋河股份', '其他'],
            '权重': [39.6, 18.6, 18.4, 20.6, 21.8, 81.0],
            '风险贡献': [35.2, 22.1, 18.5, 15.8, 8.4, 0.0],
            '边际风险': [0.89, 1.19, 1.01, 0.77, 0.39, 0.0]
        })
        
        create_bar_chart(
            risk_contribution.head(5),
            x_col='股票',
            y_col='风险贡献',
            title="个股风险贡献",
            height=300
        )
    
    with col2:
        # 行业风险贡献
        industry_risk = pd.DataFrame({
            '行业': ['食品饮料', '电子', '银行', '通信', '房地产'],
            '权重': [48.4, 18.6, 41.3, 18.4, 7.5],
            '风险贡献': [42.8, 22.1, 25.6, 8.5, 1.0]
        })
        
        create_bar_chart(
            industry_risk,
            x_col='行业',
            y_col='风险贡献',
            title="行业风险贡献",
            height=300
        )
    
    # 相关性分析
    st.subheader("相关性分析")
    
    # 模拟相关性矩阵
    correlation_data = pd.DataFrame({
        '股票1': ['平安银行', '万科A', '浦发银行', '招商银行', '五粮液'],
        '股票2': ['招商银行', '平安银行', '招商银行', '浦发银行', '贵州茅台'],
        '相关系数': [0.85, 0.32, 0.78, 0.78, 0.65],
        '风险等级': ['高', '低', '高', '高', '中']
    })
    
    create_data_table(correlation_data, "主要持仓相关性")
    
    # 压力测试
    st.subheader("压力测试")
    
    # 压力测试场景
    stress_scenarios = pd.DataFrame({
        '压力场景': ['市场下跌10%', '市场下跌20%', '行业轮动', '利率上升', '流动性紧张'],
        '组合损失': ['-8.5%', '-16.8%', '-5.2%', '-3.8%', '-6.5%'],
        '最大个股损失': ['-12.3%', '-24.6%', '-8.9%', '-5.2%', '-9.8%'],
        '恢复时间': ['15天', '45天', '8天', '12天', '20天']
    })
    
    create_data_table(stress_scenarios, "压力测试结果")
    
    # 风险监控
    st.subheader("风险监控指标")
    
    risk_metrics = pd.DataFrame({
        '风险指标': ['组合波动率', '跟踪误差', '信息比率', '最大回撤', 'VaR(95%)', 'CVaR(95%)'],
        '当前值': ['16.8%', '4.2%', '1.45', '-8.5%', '-2.3%', '-3.8%'],
        '目标值': ['<18%', '<5%', '>1.2', '<-10%', '<-3%', '<-5%'],
        '状态': ['正常', '正常', '优秀', '正常', '正常', '正常']
    })
    
    create_data_table(risk_metrics, "风险监控")


def render_performance_attribution_tab():
    """渲染绩效归因标签页"""
    st.header("绩效归因分析")
    
    # 归因概览
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card("总超额收益", "+6.2%", "📈", delta="1.8%", delta_color="normal")
    
    with col2:
        create_metric_card("选股贡献", "+4.5%", "🎯", delta="1.2%", delta_color="normal")
    
    with col3:
        create_metric_card("配置贡献", "+1.7%", "⚖️", delta="0.6%", delta_color="normal")
    
    with col4:
        create_metric_card("交互效应", "+0.3%", "🔄", delta="0.1%", delta_color="normal")
    
    st.divider()
    
    # Brinson归因分析
    st.subheader("Brinson归因分析")
    
    brinson_attribution = pd.DataFrame({
        '行业': ['银行', '食品饮料', '电子', '通信', '房地产', '医药'],
        '组合权重': ['41.3%', '48.4%', '18.6%', '18.4%', '7.5%', '0%'],
        '基准权重': ['35.2%', '42.1%', '15.8%', '12.3%', '8.9%', '5.2%'],
        '组合收益': ['15.2%', '22.8%', '18.5%', '25.3%', '-5.2%', '0%'],
        '基准收益': ['12.8%', '18.9%', '16.2%', '20.1%', '-3.8%', '8.5%'],
        '配置效应': ['+0.78%', '+1.19%', '+0.45%', '+1.23%', '+0.18%', '-0.44%'],
        '选股效应': ['+0.99%', '+1.89%', '+0.43%', '+0.96%', '-0.11%', '0%'],
        '交互效应': ['+0.15%', '+0.24%', '+0.06%', '+0.32%', '-0.02%', '0%']
    })
    
    create_data_table(brinson_attribution, "Brinson归因分析")
    
    # 归因图表
    col1, col2 = st.columns(2)
    
    with col1:
        # 配置效应
        allocation_effect = brinson_attribution[['行业', '配置效应']].copy()
        allocation_effect['配置效应'] = allocation_effect['配置效应'].str.rstrip('%').astype(float)
        
        create_bar_chart(
            allocation_effect,
            x_col='行业',
            y_col='配置效应',
            title="行业配置效应",
            height=300
        )
    
    with col2:
        # 选股效应
        selection_effect = brinson_attribution[['行业', '选股效应']].copy()
        selection_effect['选股效应'] = selection_effect['选股效应'].str.rstrip('%').astype(float)
        
        create_bar_chart(
            selection_effect,
            x_col='行业',
            y_col='选股效应',
            title="行业选股效应",
            height=300
        )
    
    # 个股贡献分析
    st.subheader("个股贡献分析")
    
    stock_contribution = pd.DataFrame({
        '股票': ['贵州茅台', '海康威视', '中兴通讯', '平安银行', '五粮液', '洋河股份'],
        '权重': ['39.6%', '18.6%', '18.4%', '20.6%', '10.4%', '21.8%'],
        '收益率': ['+3.78%', '+2.56%', '+4.56%', '+2.46%', '+2.12%', '+4.09%'],
        '收益贡献': ['+1.50%', '+0.48%', '+0.84%', '+0.51%', '+0.22%', '+0.89%'],
        '超额贡献': ['+0.85%', '+0.32%', '+0.65%', '+0.28%', '+0.15%', '+0.58%']
    })
    
    create_data_table(stock_contribution, "个股收益贡献")
    
    # 时间序列归因
    st.subheader("时间序列归因")
    
    # 模拟时间序列归因数据
    time_attribution = pd.DataFrame({
        '日期': pd.date_range(start='2024-01-01', end='2024-01-15', freq='D'),
        '总超额': [0.1, 0.3, 0.2, 0.5, 0.8, 1.2, 1.0, 1.5, 1.8, 2.1, 2.5, 2.8, 3.2, 3.8, 4.2],
        '选股贡献': [0.08, 0.22, 0.15, 0.35, 0.58, 0.85, 0.72, 1.08, 1.25, 1.48, 1.75, 1.95, 2.25, 2.65, 2.95],
        '配置贡献': [0.02, 0.08, 0.05, 0.15, 0.22, 0.35, 0.28, 0.42, 0.55, 0.62, 0.75, 0.85, 0.95, 1.15, 1.25]
    })
    
    create_line_chart(
        time_attribution,
        x_col='日期',
        y_col='总超额',
        title="累计超额收益归因",
        height=300
    )


def render_optimization_tab():
    """渲染优化建议标签页"""
    st.header("组合优化建议")
    
    # 优化目标设置
    st.subheader("优化目标设置")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        optimization_target = st.selectbox("优化目标", [
            "最大化夏普比率", "最小化风险", "最大化收益", "风险平价", "等权重"
        ])
    
    with col2:
        risk_tolerance = st.slider("风险容忍度", 0.1, 0.3, 0.18, 0.01)
    
    with col3:
        max_weight = st.slider("单股最大权重(%)", 5, 30, 15)
    
    # 约束条件
    with st.expander("约束条件设置"):
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("行业约束")
            max_industry_weight = st.slider("单行业最大权重(%)", 20, 60, 40)
            min_industry_count = st.number_input("最少行业数量", 3, 10, 5)
        
        with col2:
            st.subheader("个股约束")
            min_stock_weight = st.slider("单股最小权重(%)", 0, 5, 1)
            max_stock_count = st.number_input("最大持股数量", 10, 50, 20)
    
    # 运行优化
    if st.button("运行组合优化", type="primary"):
        with st.spinner("正在优化组合..."):
            # 模拟优化过程
            progress_bar = st.progress(0)
            for i in range(100):
                progress_bar.progress(i + 1)
            
            st.session_state.optimization_completed = True
            show_success_message("组合优化完成")
    
    # 优化结果
    if st.session_state.get('optimization_completed', False):
        render_optimization_results()


def render_optimization_results():
    """渲染优化结果"""
    st.subheader("优化结果")
    
    # 优化前后对比
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("预期收益", "19.8%", "+1.3%")
    
    with col2:
        st.metric("预期风险", "15.2%", "-1.6%")
    
    with col3:
        st.metric("夏普比率", "2.15", "+0.23")
    
    # 权重调整建议
    st.subheader("权重调整建议")
    
    weight_changes = pd.DataFrame({
        '股票': ['贵州茅台', '海康威视', '中兴通讯', '平安银行', '五粮液', '洋河股份'],
        '当前权重': ['39.6%', '18.6%', '18.4%', '20.6%', '10.4%', '21.8%'],
        '建议权重': ['25.0%', '15.0%', '15.0%', '15.0%', '12.0%', '18.0%'],
        '权重变化': ['-14.6%', '-3.6%', '-3.4%', '-5.6%', '+1.6%', '-3.8%'],
        '调整方向': ['减持', '减持', '减持', '减持', '增持', '减持'],
        '调整金额': ['-70.8万', '-17.5万', '-16.5万', '-27.2万', '+7.8万', '-18.4万']
    })
    
    create_data_table(weight_changes, "权重调整建议")
    
    # 优化效果预测
    st.subheader("优化效果预测")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 风险收益对比
        risk_return = pd.DataFrame({
            '组合': ['当前组合', '优化组合', '基准'],
            '预期收益': [18.5, 19.8, 12.3],
            '预期风险': [16.8, 15.2, 18.2]
        })
        
        # 这里应该创建散点图，但简化为表格显示
        create_data_table(risk_return, "风险收益对比")
    
    with col2:
        # 行业配置对比
        sector_comparison = pd.DataFrame({
            '行业': ['银行', '食品饮料', '电子', '通信', '房地产'],
            '当前配置': ['41.3%', '48.4%', '18.6%', '18.4%', '7.5%'],
            '优化配置': ['30.0%', '35.0%', '15.0%', '15.0%', '5.0%'],
            '变化': ['-11.3%', '-13.4%', '-3.6%', '-3.4%', '-2.5%']
        })
        
        create_data_table(sector_comparison, "行业配置对比")
    
    # 实施建议
    st.subheader("实施建议")
    
    implementation_plan = pd.DataFrame({
        '阶段': ['第一阶段', '第二阶段', '第三阶段'],
        '时间': ['1-3天', '4-7天', '8-15天'],
        '调整内容': ['减持超配股票', '增持低配股票', '微调平衡'],
        '预期影响': ['降低集中度风险', '提升收益预期', '优化风险收益比']
    })
    
    create_data_table(implementation_plan, "实施计划")
    
    # 风险提示
    st.warning("⚠️ 优化建议仅供参考，实际调整需要考虑市场环境、流动性、交易成本等因素。")